﻿using System.Collections.Concurrent;
using System.IO;
using KinonekoSoftware.CodariaDB.Presets;
using KinonekoSoftware.Studio.Models.Shells;


namespace KinonekoSoftware.Studio.Resources.Converters
{
    public sealed class IconConverter: ImageConverterBase<IconSystem>
    {
        private Bitmap _default;

        protected override ConcurrentDictionary<string, WeakReference<object>> GetCache() => Platform.ThumbnailCache;

        protected override Bitmap GetFallbackImage()
        {
            if (_default is null)
            {
                var    icon  = IconSystem.GetPresetIconFilePath(Engine.Workspace);
                var    setting = Ioc.Get<JuXiaoYouSetting>();
                byte[] buffer;
                if (setting.Preset_Icon == Preset_Icon.Override)
                {
                    if (File.Exists(icon))
                    {
                         buffer = File.ReadAllBytes(icon);
                        _default = MediaFactory.ToBitmap(buffer);
                        return _default;
                    }

                    setting.Preset_Icon = Preset_Icon.Icon_5;
                }
                
                
                buffer   = IconSystem.GetPresetIcon(setting.Preset_Icon);
                _default = MediaFactory.ToBitmap(buffer);
            }
            
            return _default;
        }
    }
}